<template>

  <el-dialog :title="title" :close-on-click-modal="false" :close-on-press-escape="false" v-model="open"
    class="form-dialog  form-dialog-large" append-to-body v-loading="!formInitialed">
    <el-form ref="editForm" :model="form" :rules="rules" label-width="120px" v-if="formInitialed">

      <el-form-item label="账号ID：" prop="账号ID">
        <el-input v-model="form['账号ID']" placeholder="请输入账号ID" :disabled="item?.recordId" />
      </el-form-item>
      <el-form-item label="账号偏好：">
        <preference-panel v-model="preferenceForm" :show-save="false"/>
      </el-form-item>





    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(editForm)">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>

  </el-dialog>

</template>
<script setup lang="ts">
import { ref, reactive, watch, toRefs, onMounted, toRaw } from 'vue'
import * as accountService from '@/api/service/AccountService'
import PreferencePanel from '@/components/feishu/PreferencePanel.vue'
import { FormInstance } from 'element-plus';


const globalVal = globalThis as any;
defineOptions({ name: "PreferenForm" });

const props = defineProps({
  item: {
    type: Object
  }
})


const emit = defineEmits(['update:item', 'success'])


const formInitialed = ref(false)
const preferenceForm = ref<any>(null)
const editForm = ref<FormInstance>()
const open = ref(true)
const title = ref(props.item?.recordId ? '修改偏好配置' : '新增偏好配置')
const data = reactive({
  form: {
    recordId: null,
    '账号ID': null,
    '偏好设置': ''
  },
  rules: {
    '账号ID': [{ required: true, message: "请选择账号ID", trigger: "blur" }],

  }
})

const { form, rules } = toRefs(data)
function reset(): void {
  data.form = {
    recordId: null,
    '账号ID': null,
    '偏好设置': ''
  }
}

/**
 * 初始化
 */
function init(recordId?: number): void {
  // todo
  if (recordId) {
    const record = toRaw(props.item) as any
    form.value = {
      recordId: record.recordId,
      '账号ID': record['账号ID'],
      '偏好设置': record['偏好设置']
    }
    console.log(form.value)
    preferenceForm.value = {
      accountId: form.value['账号ID'],
      preference: JSON.parse(record['偏好设置']),
      recordId: form.value.recordId
    }
    formInitialed.value = true;

  }
  else {
    formInitialed.value = true;
  }

}

/**
 * 提交
 */
function submitForm(formEl: FormInstance|undefined): void {
  if(!formEl){
    return ;
  }
  formEl.validate(valid => {
    if (valid) {
      globalVal.showLoading()
      form.value = {
        recordId: form.value.recordId,
        '账号ID': form.value['账号ID'],
        '偏好设置': JSON.stringify(toRaw(preferenceForm.value.preference))
      }

      if (form.value.recordId != undefined) {
        accountService.updateRecord(form.value.recordId, form.value).then(response => {
          globalVal.success("修改成功");
          open.value = false;
          emit('success', response.data.record)
        }).catch(e => {
          console.log(e);
          globalVal.error('修改失败')
        }).finally(() => {
          globalVal.hideLoading()
        });
      } else {
        accountService.addRecord(form.value).then(response => {
          globalVal.success("新增成功");
          open.value = false;
          emit('success', response.data.record)
          reset();
        }).catch(e => {
          console.log(e);
          globalVal.error('新增失败')
        }).finally(() => {
          globalVal.hideLoading()
        });
      }
    }
  });
}

/**
 * 取消
 */
function cancel(): void {
  open.value = false;
}

watch(open, (newVal) => {
  if (!newVal) {
    emit('update:item', null)
  }
})



let timer : any|null = null;
watch(() => form.value['账号ID'], ()=>{
  if(props.item?.recordId){
    return ;
  }
  if(timer){
    clearTimeout(timer);
  }
  timer = setTimeout(()=>{
    const accountId = form.value['账号ID']
    if(!accountId){
      return ;
    }
    accountService.findByAcountId(accountId).then(record=>{
      if(record){
        globalVal.error('当前账号ID已存在');
        return;
      }

      preferenceForm.value = {
        accountId:form.value['账号ID'],
        preference: null,
        recordId: null
      }


    })
    clearTimeout(timer)
  }, 300)



  // const account = accounts.filter(item => item['账号ID'] === form.value.accountId) [0]
  // let preferenceJson = null;
  // let recordId = null;
  // if(account && account['偏好设置']){
  //   preferenceJson = JSON.parse(account['偏好设置'])
  //   recordId = account.recordId;
  // }
  // preferenceForm.value = {
  //   accountId:form.value.accountId,
  //   preference: preferenceJson,
  //   recordId: recordId
  // }
})


onMounted(() => {
  reset();


  if (props.item?.recordId) {
    init(props.item.recordId);
  }
  else {
    init();
  }
})

</script>
<style lang="scss" scoped>
.category-second {
  margin-left: 10px;
}

.commission {
  margin-right: 10px;
}
</style>
